﻿// 
// 创建人：宋欣
// 创建时间：2015-04-08
// 功能：文件上传路径
// Copyright (c) 2014 宋欣. All rights reserved.
// 

using System;
using System.Configuration;
using System.IO;
using System.Web;
using HBMS.Common;
using Newtonsoft.Json.Linq;

namespace HBMS.Web.CommonAjax
{
    /// <summary>
    ///     ajax_File 的摘要说明
    /// </summary>
    public class ajax_File : BaseHandler
    {
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            try
            {
                HttpPostedFile file = context.Request.Files["file1"];
                if (file != null)
                {
                    ////文件web地址
                    string webPath = ConfigurationManager.AppSettings["FilePath"] + DateTime.Now.ToString("yyyyMMdd") +
                                     "/";
                    ////文件存放路径
                    string filePath = context.Server.MapPath(webPath);
                    ////如果文件路径不存在。创建一个。
                    if (Directory.Exists(filePath) == false)
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    ////获取文件信息
                    FileInfo fileInfo = new FileInfo(file.FileName);
                    string oldName = fileInfo.Name;
                    ////文件扩展名
                    string fileExtend = oldName.Substring(oldName.LastIndexOf("."));
                    ////文件新名
                    string newName = DateTime.Now.Ticks + fileExtend;
                    ////保存文件
                    file.SaveAs(filePath + newName);
                    WriteResult =
                        JToken.FromObject(new { result = 1, filename = oldName, path = webPath + newName })
                              .ToString();
                }
                else
                {
                    WriteResult = JToken.FromObject(new { result = 0, msg = Resources.Msg.errorFileUploadNoFile }).ToString();
                }
               
            }
            catch (Exception e)
            {
                WriteResult = JToken.FromObject(new {result = 0, msg = e.Message.ReplaceExceptionMessage()}).ToString();
            }
            ResponseWrite();
        }
    }
}